<!--会议通知 receipt-->
<template>
    <Layout>
        <Form ref="queryForm" :model="dataToQuery" :label-width="120">
            <Row v-show="!switchFlag" class="query-form" >

                <Col span="8">
                    <FormItem label='会议名称：'>
                        <Input  type='text' v-model='dataToQuery.noticName'></Input>
                    </FormItem>
                </Col>


                <Col span="8">
<!--                    <Button @click="switchQuery(true)" class="ivu-btn-switch" type="text">展开∨</Button>-->
                    <Button @click="reseter" class="ivu-btn-reset"  >重置</Button>
                    <Button type="primary" class="ivu-btn-query"   icon="md-search"  @click="query">查询</Button>
                </Col>
            </Row>
            <Row v-show="switchFlag" class="query-form">




            </Row>
            <Row v-show="switchFlag" class="query-form">


                <Col span="8" :offset="8">
                    <Button @click="switchQuery(false)" class="ivu-btn-switch" type="text">收起∧</Button>
                    <Button @click="reseter" class="ivu-btn-reset">重置</Button>
                    <Button class="ivu-btn-query" icon="md-search" @click="query">查询</Button>
                </Col>

            </Row>

            <Row class="query-form">
                <Col span="24">
                    <Button size="large"  class="ivu-btn-add" icon="md-add"  @click="addInfo">新增</Button>
                </Col>
            </Row>
        </Form>
        <Table ref='table' :height="tableHeight"  no-data-text="没有查询到相关数据!" @on-selection-change = 'getSelectRows' :loading='pageStatus.loading ||  pageStatus.baseLoading'
               border :columns="columns1"  :data="dataTable" >
        </Table>
        <Row style="margin-right:10px;">
            <Col span="24" >
                <Page style="float: right" :total="pagedata.total" :page-size="pagedata.pageSize" @on-change="pageChange1" @on-page-size-change="pageSizeChange1" :page-size-opts="pageSizeArray" show-total show-sizer show-elevator />
            </Col>
        </Row>
        <Modal  :title="mode == 'view' ?'会议通知详情':'会议通知'" :transfer=false :mask-closable="false" v-model="dataToView" v-if="dataToView && dialogShow" :width=850 :styles="{height:'559px'}"  class-name='limit-height-dialog'>
            <Row>
                <Col span="24">
                    <Tabs value="name1" >
                        <TabPane label="会议通知" name="name1">
                            <Form ref="dataToView" :class="mode === 'view'?'modal-view-detail':'modal-form'" :show-message="false" :model="dataToView" :rules="mode === 'view'?{} :ruleCustom"  :label-position="mode === 'view'?'right':'top'" :label-width="mode === 'view'?160:null" >

                                    <Row type="flex" justify="space-around" class="code-row-bg">
                                        <Col span="11">
                                            <FormItem label='会议名称：' prop='noticName'>
                                                <div v-if="mode === 'view'">{{ dataToView.noticName }}</div>
                                                <Input v-else class=''placeholder="请填写会议名称" type='text' v-model='dataToView.noticName'></Input>
                                            </FormItem>
                                        </Col>
                                        <Col span="11">
                                            <FormItem label='会议时间：' prop='noticDate'>
                                                <div v-if="mode === 'view'">{{ showDate(dataToView.startDate,dataToView.endDate)}}</div>
                                                <DatePicker v-else class="w" placeholder="请选择会议时间" type="daterange" v-model='noticDate' ></DatePicker>
                                            </FormItem>
                                        </Col>
                                    </Row>

                                    <Row type="flex" justify="space-around" class="code-row-bg">
                                        <Col span="23">
                                            <FormItem label='会议地点：' prop='noticAddress'>
                                                <div v-if="mode === 'view'">{{ dataToView.noticAddress }}</div>
                                                <Input v-else class=''placeholder="请填写会议地点" type='textarea' v-model='dataToView.noticAddress' :rows="2"></Input>
                                            </FormItem>
                                        </Col>
                                    </Row>
                                    <Row type="flex" justify="space-around" class="code-row-bg">
                                        <Col span="23">
                                            <FormItem v-if="mode === 'view'" label="相关附件：">
                                                <div v-show="dataToView.idFiles.length>0" v-for="item in dataToView.idFiles">
                                                    <a @click="downloadFile(item)"><span style="color: #3399ff;margin-left: 5px">{{ item.fileName }}</span></a>
                                                </div>
                                            </FormItem>
                                            <FormItem v-else label="上传附件：">
                                                <div >
                                                    <Upload ref="upload"
                                                            :before-upload="(file) => { beforeUpload(file, 'id') }"
                                                            :show-upload-list="true"
                                                            :max-size="10240"
                                                            multiple
                                                            type="drag"
                                                            :action="fileUrl">
                                                        <div style="padding: 20px">
                                                            <Icon type="ios-cloud-upload" size="52" style="color: #3399ff"></Icon>
                                                            <p>点击将文件拖拽到这里上传</p>
                                                        </div>
                                                    </Upload>
                                                </div>
                                                <div v-show="dataToView.idFiles.length>0" v-for="item in dataToView.idFiles">
                                                    <a @click.prevent="downloadFile(item)">{{item.fileName}}</a>
                                                    <Button type="text" icon="md-trash" @click="removeFile(item.id, 'id')"
                                                            style="margin-left: 20px;margin-bottom: 3px"/>
                                                </div>
                                            </FormItem>
                                        </Col>
                                    </Row>
                                    <Row type="flex" justify="space-around" class="code-row-bg">
                                        <Col span="23">
                                            <FormItem label='会议描述：' prop='noticDesc'>
                                                <div v-if="mode === 'view'" v-html=" dataToView.noticDesc"></div>
                                                <quill-editor v-else ref="myTextEditor" v-model="dataToView.noticDesc"  style="height:240px;margin-bottom: 80px"></quill-editor>
                                            </FormItem>
                                        </Col>
                                    </Row>
                                    <Row type="flex" justify="space-around" class="code-row-bg" v-if="mode === 'view'">
                                        <Col span="11"  >
                                            <FormItem label='创建人：' prop='userName'>
                                                <div>{{ dataToView.userName }}</div>
                                            </FormItem>
                                        </Col>
                                        <Col span="11" >
                                            <FormItem label='创建时间：' prop='createDate'>
                                                <div >{{ renderViewDate(dataToView.createDate) }}</div>
                                            </FormItem>
                                        </Col>
                                    </Row>

                               <!-- -->

                        </Form>
                        </TabPane>
                        <TabPane label="通知机构"  name="name2">
                            <div >
                                <Tree ref="itemTree" :data="orgInfoTree"  :load-data="loadData" show-checkbox></Tree>
                            </div>
                        </TabPane>
                    </Tabs>
                </Col>
            </Row>
            <div slot="footer">
                <Button v-if="mode != 'view'" type="primary"  class='ivu-btn-save' @click="submit('dataToView')" >确定</Button>
                <Button v-if="mode != 'view'" type="primary"  class='ivu-btn-cancel' @click="handleCancel" >取消</Button>
                <Button v-if="mode === 'view'" class='ivu-btn-save' @click="dialogShow=false">关闭</Button>
            </div>
        </Modal>
    </Layout>
</template>

<script>
    import {Api} from '@/api/index.js'
    import {sessionStorage} from '@/common/cacheUtils.js';
    import {quillEditor} from 'vue-quill-editor'
    import {formatDate} from '@/tools/index'
    import _deepclone from 'lodash/cloneDeep'
    var cascaderDom = () => import('@/components/cascader-dom.vue');
    import pageCommonFunction from '@/components/pageCommonFunction.js'
    export default {
        components:{
            cascaderDom,quillEditor
        },
        data(){
            return {
                ...this.createCommonDataField(),
                switchFlag:false,
                orgInfoTree:[],
                traTypes:[],
                traMethods:[],
                noticDate:[null,null],
                columns1: [
                    { title: '序号', width: 80, fixed: 'left', align: 'center', render: this.indexColumnsRender},
                    { key:'noticName',title: '会议名称',  align: 'center' },
                    { key:'noticDate',title: '会议时间',  align: 'center' ,
                        render: (h, params) => {
                        if (params.row.startDate != null&&params.row.endDate != null){
                            let startDate = new Date(params.row.startDate);
                            let endDate = new Date(params.row.endDate);
                            return h('span', startDate.getFullYear() + '/' + (startDate.getMonth() + 1) + '/' + startDate.getDate() + ' ~ ' +
                                endDate.getFullYear() + '/' + (endDate.getMonth() + 1) + '/' + endDate.getDate())
                        }
                            return h('span', "")
                        }},
                    { key:'noticAddress',title: '会议地点',  align: 'center' },
                  /*  { key:'noticDesc',title: '会议内容',  align: 'center' ,ellipsis:true},*/

               {
                    title: '操作',
                    key: 'action',
                    fixed: 'right',
                    width: 200,
                    align: 'center',
                    render: (h, params) => {
                        if (this.currentUser.loginId === this.Common.admin || this.currentUser.userId === params.row.createUserId || this.currentUser.userRole.find(obj => obj.roleId == '73b38b37dff64392ba0ee7dd579bf293') != undefined
                            ||sessionStorage('userId').getObject('userId').userBeHandedOver.find(obj => obj == params.row.createUserId) != undefined) {
                            return h('div', [
                                h('A', {
                                    props: {type: 'primary', size: 'small'},
                                    style: {fontSize: '14px',},
                                    on: {
                                        click: () => {
                                            this.viewDataTo(params);
                                        }
                                    }
                                }, '详情'),
                                h('Divider', {props: {type: 'vertical'}}, ''),
                                h('A', {
                                    props: {type: 'primary', size: 'small'},
                                    disabled: true,
                                    style: {fontSize: '14px'},
                                    on: {
                                        click: () => {
                                            this.showdata(params);
                                        }
                                    }
                                }, '修改'),
                                h('Divider', {props: {type: 'vertical'}}, ''),
                                h('A', {
                                    props: {type: 'primary', size: 'small'},
                                    style: {fontSize: '14px', color: 'red'},
                                    on: {
                                        click: () => {
                                            this.deleteData(params);
                                        }
                                    }
                                }, '删除')
                            ]);
                        } else {
                            return h('div', [
                                h('A', {
                                    props: {type: 'primary', size: 'small'},
                                    style: {fontSize: '14px',},
                                    on: {
                                        click: () => {
                                            this.viewDataTo(params);
                                        }
                                    }
                                }, '详情'),
                                h('Divider', {props: {type: 'vertical'}}, ''),
                                h('A', {
                                    props: {type: 'primary', size: 'small'},
                                    style: {fontSize: '14px', color: '#c5c8ce'}
                                }, '修改'),
                                h('Divider', {props: {type: 'vertical'}}, ''),
                                h('A', {
                                    props: {type: 'primary', size: 'small'},
                                    style: {fontSize: '14px', color: '#c5c8ce'}
                                }, '删除')
                            ]);
                        }
                    }
                }
                ],
                ruleCustom : {

                    noticName: [ { required: true, message: '请填写会议名称', trigger: 'change',}],
                    noticDate: [ {
                        validator: (rule, value, callback) => {
                            if (this.noticDate == null || this.noticDate[0] == null || this.noticDate[1] == null) {
                                callback(' ')
                            } else {
                                callback()
                            }
                        },
                        required: true,
                        trigger: 'change'
                    }],
                    noticAddress: [ { required: true, message: '请填写会议地点', trigger: 'change',}],

                },
                tableHeight:10,
                traTypeList:[],
                traMethodsList:[],
                // api
                standardSelectModal:false,
                queryUrl:Api.queryMeetingNotic,
                deleteUrl:Api.deleteMeetingNotic,
                updateUrl:Api.updateMeetingNotic,
                saveUrl:Api.saveMeetingNotic,
            }
        },
        mounted() {
            this.dataToQuery ={};
            this.setTableHeight();
            this.query();
            this.getOrgInfoTree();
        },
        methods:{

            ...pageCommonFunction,
            deleteData(params) {
                this.deleteDateById(params.row.id);
            },
            getOrgInfoTree(){
                let companyId = sessionStorage('userId').getObject('userId').companyId;
                let companyName = sessionStorage('userId').getObject('userId').companyName;
                this.orgInfoTree = [{orgId:companyId,title:companyName,children:[],expand:true}];
                this.$http.get(Api.queryOrg, {
                    params: {
                        parentId: companyId,
                        codeAffordIf : 0
                    }
                }).then(res => {
                    res.data.data.map(i => {
                        i.title = i.orgName;
                        delete i['orgName'];
                        i.loading = false;
                        i.children = [];
                    });
                    this.$set(this.orgInfoTree[0],'children',res.data.data);
                }).catch(e => {
                    this.$Message.error('请求失败');
                })
            },
            async getOrgInfoTreeByProposalId(proposalId){
                let companyId = sessionStorage('userId').getObject('userId').companyId;
                let companyName = sessionStorage('userId').getObject('userId').companyName;
                this.orgInfoTree = [{orgId:companyId,title:companyName,children:[],expand:true}];
                await this.$http.get(Api.queryOrgByProposalId+"/"+companyId+
                    "/"+proposalId).then(res => {
                    res.data.data.map(i => {
                        i.title = i.orgName;
                        delete i['orgName'];
                        i.loading = false;
                        i.children = [];
                    })
                    this.$set(this.orgInfoTree[0],'children',res.data.data);
                }).catch(e => {
                    this.$Message.error('请求失败');
                })
            },
            loadData(item, callback) {

                item.loading = true;
                if(this.mode === 'add'){
                    this.$http.get(Api.queryOrg, {
                        params: {
                            parentId: item.orgId,
                            codeAffordIf : 0
                        }
                    }).then(res => {
                        item.loading = false;
                        if(res.data.data.length !== 0) {
                            res.data.data.map(i => {
                                i.title = i.orgName
                                delete i['orgName']
                                i.loading = false;
                                i.children = [];
                            })
                            item.children = res.data.data;
                            callback(item.children);
                        } else {
                            delete item['children'];
                            delete item['loading'];
                        }
                    }).catch(e => {
                        console.log(e);
                        this.$Message.error('请求失败');
                    })
                }else{
                    this.$http.get(Api.queryOrgByProposalId+"/"+item.orgId+"/"+this.dataToView.id).then(res => {
                        item.loading = false;
                        if(res.data.data.length !== 0) {
                            res.data.data.map(i => {
                                i.title = i.orgName
                                delete i['orgName']
                                i.loading = false;
                                i.children = [];
                            })
                            item.children = res.data.data;
                            callback(item.children);
                        } else {
                            delete item['children'];
                            delete item['loading'];
                        }
                    }).catch(e => {
                        console.log(e);
                        this.$Message.error('请求失败');
                    })
                }
            },
            async showdata(data) {
                if (this.beforeEditDialogOpen instanceof Function) {
                    await this.beforeEditDialogOpen(data)
                }
                //修改页面
                this.mode = 'edit'
                let dataToView = _deepclone(data.row);
                this.dataToView = dataToView
                this.noticDate = [new Date(data.row.startDate),new Date(data.row.endDate)];
                this.dataToView.registrant = this.currentUser.userName;
                this.dataToView.registrantPhone = this.currentUser.mobileNumber;
                this.dataToView.registTime = new Date();
                if (this.afterDataToViewInit instanceof Function) {
                    await this.afterDataToViewInit()
                }
                this.dialogShow = true;
                setTimeout(()=>{
                    this.dialogVisibleChangeHandele(this.dialogShow)
                },100);
                await this.getOrgInfoTreeByProposalId(dataToView.id);
            },
            async viewDataTo(data) {
                if (this.beforeViewDialogOpen instanceof Function) {
                    this.beforeViewDialogOpen(data)
                }
                // 查看页面
                this.mode = 'view'
                let dataToView = _deepclone(data.row);
                this.dataToView = dataToView

                if (this.afterDataToViewInit instanceof Function) {
                    await this.afterDataToViewInit()
                }
                this.dialogShow = true;
                setTimeout(()=>{
                    this.dialogVisibleChangeHandele(this.dialogShow)
                },100)
                await this.getOrgInfoTreeByProposalId(dataToView.id);

            },
            showDate(date1,date2){
                let startDate = new Date(date1);
                let endDate = new Date(date2);
                return startDate.getFullYear() + '/' + (startDate.getMonth() + 1) + '/' + startDate.getDate() + ' ~ ' + endDate.getFullYear() + '/' + (endDate.getMonth() + 1) + '/' + endDate.getDate()
            },
            switchQuery(flag) {
                this.switchFlag = flag;
                if (!this.switchFlag) {
                    this.tableHeight = this.tableHeight + 44;
                } else {
                    this.tableHeight = this.tableHeight - 44;
                }
            },
            query() {
                this.query1()
            },
            submitBase(name,dateToSubmit) {
                if (this.pageStatus.sending) return
                this.$refs[name].validate((valid) => {
                    if (valid) {
                        this.$Modal.confirm({
                            title: '提示',
                            content: '<p>是否要提交？</p>',
                            onOk: () => {
                                if (dateToSubmit === undefined) {
                                    dateToSubmit = _deepclone(this.dataToView)
                                }
                                let url = this.mode === 'add' ? this.saveUrl : this.updateUrl;
                                if(this.noticDate.length == 2) {
                                    dateToSubmit.startDate = this.renderViewDate(this.noticDate[0]);
                                    dateToSubmit.endDate = this.renderViewDate(this.noticDate[1]);

                                }
                                this.pageStatus.sending = true

                                let successHandle = (res) => {
                                    if (res.data.status === 200) {
                                        let tree =  this.$refs.itemTree.getCheckedAndIndeterminateNodes();
                                        let checkNode = [];
                                        tree.map((i, j)=>{
                                            checkNode.push({proposalId:dateToSubmit.id,orgId: i.orgId,iterator:i.children.length==0?'1':'0'});
                                        });
                                        this.$http.post(Api.saveReceiptToOrg + "/"+ dateToSubmit.id,
                                            checkNode).then((res) => {}).catch(e => {
                                            console.log(e);
                                        });
                                        this.$Message.success(this.mode === 'add' ? '添加成功' : '修改成功');
                                        this.dialogShow = false;
                                        this.query1()
                                    } else if (res.data.status === 201) {
                                        this.$Message.error(res.data.msg);
                                    }
                                    this.pageStatus.sending = false
                                }
                                let failedHandle = e => {
                                    console.log(e);
                                    this.$Message.error(this.mode === 'add' ? '添加失败' : '修改失败')
                                    this.pageStatus.sending = false
                                }
                                if (this.mode === 'add'){
                                    this.$http.post(url, dateToSubmit).then(successHandle).catch(failedHandle)
                                }else{
                                    this.$http.put(url, dateToSubmit).then(successHandle).catch(failedHandle)
                                }
                            },
                            onCancel: () => {
                            }
                        });
                    } else {
                        this.$Message.error('请填报完整!');
                    }
                })
            },
            submit(name) {

                this.submitBase(name);
            },
            createEmptyDataToAdd() {
                this.getOrgInfoTree();
                this.noticDate = [null,null];
                return{
                    id:this.get_uuid(),
                }
            },
            reseter() {

                this.query1()
            },
            async afterDataToViewInit() {
                await this.getFiles('id');
            }

        },
        watch:{

        },

    }
</script>

<style lang='css' scoped>
    .rpt-form{}
    /deep/ .rpt-form .query-form-el{width:100%;}
</style>
